package com.mypage.view.activity.beautMore;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.mypage.adapter.NChageListAdapter;
import com.mypage.adapter.NDefauleChageListAdapter;
import com.mypage.bean.CustomListBean;
import com.mypage.bean.QueryCustomListBean;
import com.mypage.utils.MyListView;
import com.mypage.utils.RecordSQLiteOpenHelper;
import com.mypage.utils.UtilsShowDialog;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewInputNameActivity extends Activity {
    public List<CustomListBean.CustomData.Custom> mList;
    public List<QueryCustomListBean.CustomData.Custom> mQList;
    public NChageListAdapter mAdapter;
    public NDefauleChageListAdapter mDefaultAdapter;
    @Bind(R.id.searchData)
    TextView searchData;
    @Bind(R.id.searchDataButtonLine)
    View searchDataButtonLine;
    @Bind(R.id.noContent)
    TextView noContent;
    @Bind(R.id.noContentButtonLine)
    View noContentButtonLine;
    @Bind(R.id.textUser)
    TextView textUser;
    private UtilsShowDialog showDialog;
    @Bind(R.id.btnImgBack)
    ImageView btnImgBack;
    @Bind(R.id.etSearchContent)
    EditText etSearchContent;
    @Bind(R.id.imgClean)
    ImageView imgClean;
    @Bind(R.id.listCustom)
    MyListView listCustom;

    @Bind(R.id.listView)
    MyListView listView;
    @Bind(R.id.tv_clear)
    TextView tvClear;
    @Bind(R.id.linearLayout)
    LinearLayout linearLayout;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private BaseAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_input_name);
        ButterKnife.bind(this);
        showDialog = new UtilsShowDialog(this);
        mHttpQueryData();
//        getDataHttp();//默认访问用户列表
        textChange();
        initView();
        initListener();
    }

    public void getDataHttp() {
        showDialog.onShowLoadingDialog("正在加载...");
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "getDefaultAccessUserList");
        Log.d("request默认用户列表url", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getDefaultAccessUserList");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Log.d("request默认客户Fail", arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.d("request默认客户Success", arg0.result.toString());
                CustomListBean mCustom = new Gson().fromJson(arg0.result.toString(), CustomListBean.class);
                mList = mCustom.data.getDefaultAccessUserList;
                if (mList == null) {
                    showDialog.onDismissLoadingDialog();
                    return;
                }
                mDefaultAdapter = new NDefauleChageListAdapter(mList, NewInputNameActivity.this);
                listCustom.setAdapter(mDefaultAdapter);
                showDialog.onDismissLoadingDialog();
            }
        });
    }

    //监听输入框的变化
    public void textChange() {
        // 搜索框的文本变化实时监听
        etSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                String mContent = etSearchContent.getText().toString();
                noContent.setVisibility(View.GONE);
                noContentButtonLine.setVisibility(View.GONE);
                mHttpQueryData();
                if ("".equals(mContent)) {
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
                } else {
                    searchData.setVisibility(View.VISIBLE);
                    searchDataButtonLine.setVisibility(View.VISIBLE);
                    searchData.setText(getString(R.string.courstomsearch) + mContent + "”");
                }

//                String mContent = etSearchContent.getText().toString();
//
//                if ("".equals(mContent)){
//                    listCustom.setVisibility(View.VISIBLE);
//                    linearLayout.setVisibility(View.GONE);
//                }
//                if(!"".equals(mContent)){
//                    listCustom.setVisibility(View.GONE);
//                    linearLayout.setVisibility(View.VISIBLE);
//                }
//
//
//                String mStr = "搜索＂" + mContent + "＂";
//
//                SpannableStringBuilder builder = new SpannableStringBuilder(mStr);
//
//                //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
//
//                ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE);
//                builder.setSpan(blueSpan, 3, mStr.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                tvClear.setText(builder);

            }

            @Override
            public void afterTextChanged(Editable s) {

                String tempName = etSearchContent.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据
                queryData(tempName);

            }
        });
    }

    public void initView() {
        String user = getIntent().getStringExtra("User");
        if ("".equals("user")){
            textUser.setText("输入新所有人名称");
            return;
        }else{
            textUser.setText(user);
        }

    }

    public void initListener() {
        etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // TODO: 2017/5/11
                    showDialog.onShowLoadingDialog("正在加载...");
                    mHttpQueryData();
                    searchData.setVisibility(View.GONE);
                    searchDataButtonLine.setVisibility(View.GONE);
                    if (mQList.size() == 0) {
                        searchData.setVisibility(View.GONE);
                        searchDataButtonLine.setVisibility(View.GONE);
                        noContent.setVisibility(View.VISIBLE);
                        noContentButtonLine.setVisibility(View.VISIBLE);
                        noContent.setText(getString(R.string.pipeijieguo) + etSearchContent.getText().toString() + getString(R.string.jieguopipie));
                    }
//                    setKeyBoard();
//                    saveData();
//                    listCustom.setVisibility(View.VISIBLE);
//                    linearLayout.setVisibility(View.INVISIBLE);
//                    // TODO 根据输入的内容模糊查询商品，并跳转到另一个界面，由你自己去实现
////                    Toast.makeText(NewInputNameActivity.this, etSearchContent.getText().toString(),
////                            Toast.LENGTH_SHORT).show();
//                    mHttpQueryData();
                }
                return false;
            }
        });
        listCustom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String sName = mQList.get(position).name;
                String mIds = mQList.get(position).id;
                Intent intent = new Intent();
                intent.putExtra("Name", sName);
                intent.putExtra("mId", mIds);
                setResult(11, intent);
                finish();
            }
        });
        //搜索
        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                mHttpQueryData();
                listCustom.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                Toast.makeText(NewInputNameActivity.this, etSearchContent.getText().toString(), Toast.LENGTH_SHORT)
                        .show();
//                //删除数据库的历史记录
//                deleteData();
//                queryData("");
            }
        });
        //搜索结果的listiew
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                TextView textView = (TextView) view
                        .findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                etSearchContent.setText(name);
//                Toast.makeText(NewInputNameActivity.this, name + " 来了啊", Toast.LENGTH_SHORT)
//                        .show();
                // TODO 获取到item上面的文字，根据该关键字跳转到另一个页面查询，由你自己去实现
            }
        });
        // 插入数据，便于测试，否则第一次进入没有数据怎么测试呀？
//        Date date = new Date();
//        long time = date.getTime();
//        insertData("Leo" + time);

        // 第一次进入查询所有的历史记录
        queryData("");
    }

    @OnClick(R.id.searchData)
    public void searchData() {
        showDialog.onShowLoadingDialog("正在加载...");
        mHttpQueryData();
        searchData.setVisibility(View.GONE);
        searchDataButtonLine.setVisibility(View.GONE);
        if (mQList.size() == 0) {
            searchData.setVisibility(View.GONE);
            searchDataButtonLine.setVisibility(View.GONE);
            noContent.setVisibility(View.VISIBLE);
            noContentButtonLine.setVisibility(View.VISIBLE);
            noContent.setText(getString(R.string.pipeijieguo) + etSearchContent.getText().toString() + getString(R.string.jieguopipie));
        }
//    Toast.makeText(this,"sssssssssss",3).show();
    }

    @OnClick({R.id.btnImgBack, R.id.imgClean})
    public void setOnClick(ImageView v) {
        switch (v.getId()) {
            case R.id.imgClean:
                etSearchContent.setText("");
                break;
            case R.id.btnImgBack:
                finish();
                break;

        }
    }


    /**
     * 点击按钮隐藏键盘
     */
    public void setKeyBoard() {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getApplicationContext().
                getSystemService(NewInputNameActivity.this.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(etSearchContent.getWindowToken(), 0); //隐藏
    }


    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%"
                        + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[]{"name"}, new int[]{android.R.id.text1},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?",
                new String[]{tempName});
        // 判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }


    public void saveData() {
        // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
        boolean hasData = hasData(etSearchContent.getText()
                .toString().trim());
        if (!hasData) {
            insertData(etSearchContent.getText().toString()
                    .trim());
            queryData("");
        }
    }

    public void mHttpQueryData() {
//        showDialog.onShowLoadingDialog("正在加载...");
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance().getServerBinding());
        params.addBodyParameter("serviceName", "getKeyNameUserList");
        params.addBodyParameter("keyName", etSearchContent.getText().toString());


        Log.d("request查询用户列表url", UrlManager.getInterfaceUrl() + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getKeyNameUserList&" + "keyName="+etSearchContent.getText().toString());
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Log.d("request查询客户Fail", arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                showDialog.onDismissLoadingDialog();
                Log.d("request查询客户Success", arg0.result.toString());
                QueryCustomListBean mCustom = new Gson().fromJson(arg0.result.toString(), QueryCustomListBean.class);
                mQList = mCustom.data.getKeyNameUserList;
                if (mQList == null) {
                    showDialog.onDismissLoadingDialog();
                    return;
                }
                mAdapter = new NChageListAdapter(mQList, NewInputNameActivity.this, etSearchContent.getText().toString());
                listCustom.setAdapter(mAdapter);
                showDialog.onDismissLoadingDialog();
            }
        });


    }
}
